package flc.ast.activity;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.tabs.TabLayout;
import com.stark.cartoonavatarmaker.lib.core.AvatarColorType;
import com.stark.cartoonavatarmaker.lib.core.AvatarConst;
import com.stark.cartoonavatarmaker.lib.core.AvatarPartBean;
import com.stark.cartoonavatarmaker.lib.core.AvatarPartType;
import com.stark.cartoonavatarmaker.lib.core.AvatarRedoUndoController;
import com.stark.cartoonavatarmaker.lib.core.AvatarTemplatePart;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.bean.MyRecordBean;
import flc.ast.databinding.ActivityDressUpBinding;
import flc.ast.fragment.DressUpColorFragment;
import flc.ast.fragment.DressUpFragment;
import flc.ast.fragment.TemplateFragment;
import flc.ast.utils.AppSpUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.redo.RedoUndoController;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.view.container.StkLinearLayout;

public class DressUpActivity extends BaseAc<ActivityDressUpBinding> implements RedoUndoController.IListener<AvatarTemplatePart> {

    private List<Fragment> mFragments = new ArrayList<>();
    private List<String> mTitles = new ArrayList<>();
    private String mTmpShareFilePath;
    private AvatarRedoUndoController mRedoUndoController;
    private static AvatarTemplatePart sTemplatePart;

    public static void start(@NonNull Context context, @Nullable AvatarTemplatePart templatePart) {
        Intent intent = IntentUtil.getIntent(context, DressUpActivity.class);
        sTemplatePart = templatePart;
        context.startActivity(intent);
    }

    @Override
    protected int onCreate() {
        return R.layout.activity_dress_up;
    }

    @Override
    protected void initView() {
        mDataBinding.ivDressUpBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mRedoUndoController = new AvatarRedoUndoController();
        mRedoUndoController.addListener(this);
        initFragments();
        for (int i = 0; i < mTitles.size(); i++) {
            mDataBinding.tabLayout.addTab(mDataBinding.tabLayout.newTab().setText(mTitles.get(i)));
        }
        mDataBinding.viewPager.setAdapter(new DressUpActivity.MyPagerAdapter(getSupportFragmentManager()));
        mDataBinding.tabLayout.setupWithViewPager(mDataBinding.viewPager);
        //给tab每个item设置值
        for (int i = 0; i < mDataBinding.tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mDataBinding.tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(i));
            }
        }
        // 设置默认第一个被选中
        View view = mDataBinding.tabLayout.getTabAt(0).getCustomView();
        TextView tv = view.findViewById(R.id.tvTabItemName);
        ImageView iv = view.findViewById(R.id.ivTabItemSel);
        iv.setVisibility(View.VISIBLE);
        tv.setTextColor(Color.parseColor("#FB54FB"));
        tv.setTextSize(18);
        //设置TabLayout点击事件
        mDataBinding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                TextView tv = view.findViewById(R.id.tvTabItemName);
                tv.setTextColor(Color.parseColor("#FB54FB"));
                tv.setTextSize(18);
                ImageView iv = view.findViewById(R.id.ivTabItemSel);
                iv.setVisibility(View.VISIBLE);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                TextView tv = view.findViewById(R.id.tvTabItemName);
                tv.setTextColor(Color.parseColor("#FFFFFFFF"));
                tv.setTextSize(15);
                ImageView iv = view.findViewById(R.id.ivTabItemSel);
                iv.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        checkToShowUndoRedo();
        mDataBinding.ivRedo.setOnClickListener(this);
        mDataBinding.ivUndo.setOnClickListener(this);
        mDataBinding.ivSave.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivUndo:
                mRedoUndoController.undo();
                break;
            case R.id.ivRedo:
                mRedoUndoController.redo();
                break;
            case R.id.ivSave:
                getPermission();
                break;
        }
    }

    @Override
    protected void initData() {
        mDataBinding.avatarMakeView.post(new Runnable() {
            @Override
            public void run() {
                if (sTemplatePart != null) {
                    mDataBinding.avatarMakeView.setTemplatePart(sTemplatePart);
                }
                mRedoUndoController.addDo(mDataBinding.avatarMakeView.getTemplatePart());
            }
        });
    }

    @Override
    public void onDoChanged() {
        checkToShowUndoRedo();
    }

    @Override
    public void onRedo(AvatarTemplatePart value) {
        mDataBinding.avatarMakeView.setTemplatePart(value);
        checkToShowUndoRedo();
    }

    @Override
    public void onUndo(AvatarTemplatePart value) {
        mDataBinding.avatarMakeView.setTemplatePart(value);
        checkToShowUndoRedo();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(mTmpShareFilePath)) {
            FileUtils.delete(mTmpShareFilePath);
            mTmpShareFilePath = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRedoUndoController.delListener(this);
        mRedoUndoController.clear();
    }

    private void initFragments() {
        mFragments.clear();
        mTitles.clear();

        for (AvatarPartType type : AvatarPartType.values()) {
            mFragments.add(DressUpFragment.newInstance(type));
            mTitles.add(AvatarConst.getAvatarPartTitle(type));
            if (type == AvatarPartType.body) {
                mFragments.add(DressUpColorFragment.newInstance(AvatarColorType.SKIN));
                mTitles.add(getString(R.string.cam_skin_color));
            } else if (type == AvatarPartType.eyeball) {
                mFragments.add(DressUpColorFragment.newInstance(AvatarColorType.EYE_BALL));
                mTitles.add(getString(R.string.cam_eyeball_color));
            } else if (type == AvatarPartType.hair) {
                mFragments.add(DressUpColorFragment.newInstance(AvatarColorType.HAIR));
                mTitles.add(getString(R.string.cam_hair_color));
            }
        }
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO).reqPermissionDesc(getString(R.string.get_save_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                save();
            }
        }).request();
    }

    private void save() {
        showDialog(getString(com.stark.common.res.R.string.saving));
        Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.avatarMakeView);
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                File file = ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                emitter.onNext(true);
                saveRecord(file.getPath());
            }

            @Override
            public void accept(Boolean save) {
                int msgId = com.stark.common.res.R.string.save_failure;
                if (save) {
                    msgId = R.string.save_to_album;
                }
                ToastUtils.showShort(msgId);
                dismissDialog();
                startActivity(HomeActivity.class);
            }
        });
    }

    //保存记录
    private void saveRecord(String path) {
        List<MyRecordBean> listSave = new ArrayList<>();
        listSave.add(new MyRecordBean(path));
        List<MyRecordBean> listSp = AppSpUtils.getRecordList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            AppSpUtils.saveRecordList(listSp);
        } else {
            AppSpUtils.saveRecordList(listSave);
        }
    }

    private void checkToShowUndoRedo() {
        if (mRedoUndoController.canUndo()) {
            mDataBinding.ivUndo.setImageResource(R.drawable.achehui);
        } else {
            mDataBinding.ivUndo.setImageResource(R.drawable.afnachehuij);
        }
        if (mRedoUndoController.canRedo()) {
            mDataBinding.ivRedo.setImageResource(R.drawable.achehuij);
        } else {
            mDataBinding.ivRedo.setImageResource(R.drawable.afanchehui);
        }
    }

    //自定义Tab布局
    private View getTabView(int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_tab, null);
        TextView text = view.findViewById(R.id.tvTabItemName);
        text.setText(mTitles.get(i));
        text.setTextColor(Color.parseColor("#FFFFFF"));
        text.setTextSize(15);
//        StkLinearLayout llCategoryItem=view.findViewById(R.id.llTabItem);
//        llCategoryItem.setBackgroundResource(0);
//        llCategoryItem.setPadding(30,20,30,20);
        return view;
    }

    public void setAvatarPart(AvatarPartType type, AvatarPartBean partBean) {
        mDataBinding.avatarMakeView.setAvatarPart(type, partBean);
        mRedoUndoController.addDo(mDataBinding.avatarMakeView.getTemplatePart());
    }

    public void setColor(AvatarColorType type, @ColorInt int color) {
        mDataBinding.avatarMakeView.setColor(type, color);
        mRedoUndoController.addDo(mDataBinding.avatarMakeView.getTemplatePart());
    }

    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(@NonNull FragmentManager fm) {
            super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles.get(position);
        }
    }

}